package com.app.GoCuro;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.GoCuro.util.IntentIntegrator;
import com.app.GoCuro.util.IntentResult;

public class DatabaseActionsActivity extends BaseActivity {

	ArrayAdapter<String> adapter; // previous item list adapter

	// **** new code starts
	LinkedList<String> itemsLinkedList = new LinkedList<String>();
	Map<String, String> timecontentMap = new HashMap<String, String>();
	ListView previousItemsList;
	int numofItems = 0;

	// **** new code ends

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// **** new code starts
		if (savedInstanceState != null) {
			onRestoreInstanceState(savedInstanceState);
			Toast.makeText(getApplicationContext(),
					"savedInstanceState != null", Toast.LENGTH_SHORT).show();
		}
		// **** new code starts

		Bundle manualInputData = this.getIntent().getExtras();
		String sentback_Datetime = manualInputData.getString("datatime");
		String sentback_Contents = manualInputData
				.getString("manualInputContents");
		// Toast.makeText(getApplicationContext(), sentback_Datetime,
		// Toast.LENGTH_SHORT).show();
		// Toast.makeText(getApplicationContext(), sentback_Contents,
		// Toast.LENGTH_SHORT).show();

		if (sentback_Datetime != null && sentback_Contents != null) {
			numofItems++;
			itemsLinkedList.addFirst("item #" + numofItems + ": "
					+ sentback_Datetime);
			timecontentMap.put(sentback_Datetime, sentback_Contents);

		}

		// **** new code ends

		setContentView(R.layout.database_actions);
		// **** new code ends

		// **** new code starts
		// add controller for button input here
		final Button inputButton = (Button) findViewById(R.id.enter_item);
		inputButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Start MannualInputActivity

				Intent MannualInputActivityIntent = new Intent(
						DatabaseActionsActivity.this, ManualInputActivity.class);
				DatabaseActionsActivity.this
						.startActivity(MannualInputActivityIntent);

			}
		});
		// **** new code ends

		final Button scanButton = (Button) findViewById(R.id.scan_item);
		scanButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Call BarcodeScanner
				IntentIntegrator integrator = new IntentIntegrator(
						DatabaseActionsActivity.this);
				integrator.initiateScan(Collections.singleton("PDF_417"));

			}
		});

		//
		// TODO: Get the items from web client here
		//
		previousItemsList = (ListView) findViewById(R.id.previous_items);

		// ----------------unnecesary------------------
		Resources res = getResources();
		String[] testItems = res.getStringArray(R.array.test_items);

		// ***** new code
		// ArrayList<String> testItemsLst = new ArrayList<String>();
		/*
		 * for(String s : testItems){ testItemsLst.add(s); }
		 */
		// ----------------unnecesary------------------

		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, itemsLinkedList);
		previousItemsList.setAdapter(adapter);

		// get and set the database string
		String databaseName = getIntent().getStringExtra("selected_database");
		setTitle(databaseName);

		previousItemsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				String selectedItem = (String) previousItemsList
						.getItemAtPosition(pos);

				// start the new activity here, to be done in a future revision
				// **** new code starts
				int indexofFirstColon = ((TextView) arg1).getText().toString()
						.indexOf(":");
				// the is a space after the colon, so the starting index should
				// +2
				String datetime = ((TextView) arg1).getText().toString()
						.substring(indexofFirstColon + 2);
				String contents = timecontentMap.get(datetime);
				Toast.makeText(getApplicationContext(), contents,
						Toast.LENGTH_SHORT).show();
				// **** new code ends
			}

		});

	} // end onCreat

	// Get scan result from ZXing
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		IntentResult scanResult = IntentIntegrator.parseActivityResult(
				requestCode, resultCode, intent);
		// **** new code starts
		if (scanResult.getContents() != null) {
			// **** new code ends
			// handle scan result
			String contents = scanResult.toString();

			if (contents != null) {

				Toast.makeText(this, contents, Toast.LENGTH_SHORT).show();

				// **** new code starts
				Calendar c = Calendar.getInstance();
				SimpleDateFormat f = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss a");
				String formattedDateTime = f.format(c.getTime());
				timecontentMap.put(formattedDateTime, contents);

				// populate list view
				numofItems++;
				itemsLinkedList.addFirst("item #" + numofItems + ": "
						+ formattedDateTime);

				adapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_list_item_1, itemsLinkedList);
				// **** new code ends
				previousItemsList.setAdapter(adapter);

				// adapter.add(contents);
				// adapter.notifyDataSetChanged();

				//
				// TODO: send data to web server
				//
			} else {
				Toast.makeText(this, "Scan Failed", Toast.LENGTH_LONG).show();
			}

		}
		// else continue with any other code you need in the method

	}

	// **** new code starts
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		// save the number of items
		outState.putInt("numofItems", numofItems);

		// save the items list (on list view)
		ArrayList<String> itemsArrayList = new ArrayList<String>(
				itemsLinkedList);
		outState.putStringArrayList("itemsList", itemsArrayList);

		// save the hashmap<datatime, scannedcontents>
		ArrayList<String> keysArrayList = new ArrayList<String>();
		ArrayList<String> valuesArrayList = new ArrayList<String>();

		for (Object s : timecontentMap.keySet().toArray())
			keysArrayList.add(s.toString());

		for (Object s : timecontentMap.values())
			valuesArrayList.add(s.toString());

		outState.putStringArrayList("keysList", keysArrayList);
		outState.putStringArrayList("valuesList", valuesArrayList);

	}

	// **** new code ends

	// **** new code starts
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		// restore the relevant information
		numofItems = savedInstanceState.getInt("numofItems");
		itemsLinkedList = new LinkedList<String>(
				savedInstanceState.getStringArrayList("itemsList"));
		// restore the hashmap<datatime, scannedcontents>
		int i = 0;
		for (String key : savedInstanceState.getStringArrayList("keysList")) {
			timecontentMap.put(key,
					savedInstanceState.getStringArrayList("valuesList").get(i));
			i++;
		}

	}
	// **** new code ends

}
